package com.haojii.notifier.helper;

import java.util.Properties;
import java.util.logging.Logger;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class AppEngineEmailSender {

	private static final Logger log = Logger.getLogger(AppEngineEmailSender.class.getName());
	
	private static final String AppEngineAdminAccount = "jacky.jihao@gmail.com";
	
	private static String buildHTMLMsg(String subject, String bodyText) {
		StringBuffer sb = new StringBuffer();
		sb.append("<HTML http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n");
		sb.append("<HEAD>\n");
		sb.append("<TITLE>\n");
		sb.append(subject + "\n");
		sb.append("</TITLE>\n");
		sb.append("</HEAD>\n");
		sb.append("<BODY>\n");
		sb.append("<H1>" + subject + "</H1>" + "\n");
		
		sb.append(bodyText);
		sb.append("\n");
		sb.append("</BODY>\n");
		sb.append("</HTML>\n");
		
		return sb.toString();
		//msg.setDataHandler(new DataHandler(new ByteArrayDataSource(sb.toString(), "text/html")));
	}

	public static void send(String to, String subject, String bodyText) {
		log.info("Send Email to:"+to+" subject:"+subject);

		Properties props = new Properties(); 
        Session session = Session.getDefaultInstance(props, null); 
        Message msg = new MimeMessage(session); 
 
        try { 
            
            msg.setFrom(new InternetAddress(AppEngineAdminAccount)); 
            msg.addRecipients(Message.RecipientType.TO, 
            		InternetAddress.parse(to, false)); 
            msg.setSubject(subject); 
            //msg.setText(msgBody);
            
            String html = buildHTMLMsg(subject,bodyText);
            
            // 给消息对象设置内容 
            BodyPart mdp = new MimeBodyPart(); //新建一个存放信件内容的BodyPart对象 
            mdp.setContent(html, "text/html;charset=UTF-8"); //给BodyPart对象设置内容和格式/编码方式 
            Multipart mm = new MimeMultipart(); //新建一个MimeMultipart对象用来存放BodyPart对象(事实上可以存放多个) 
            mm.addBodyPart(mdp); //将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart) 
            msg.setContent(mm); //把mm作为消息对象的内容 
            
            Transport.send(msg); 
     
        } catch (Exception e) { 
        	log.warning(e.getMessage());
        } 
	}
        
		
}